package com.cipe.cmrs.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.AbstractView;

import com.cipe.cmrs.util.StreamUtil;

public class WordPdfView extends AbstractView {
    public static final String PARAM_FULL_PATH_NAME = "fullFilePath";
    private static final String CONTENT_TYPE_WORD = "application/msword";
    private static final String CONTENT_TYPE_PDF = "application/pdf";

    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String fileName = (String) model.get(PARAM_FULL_PATH_NAME);
        Assert.isTrue(fileName.endsWith(".pdf") || fileName.endsWith(".doc") || fileName.endsWith(".docx"));
        File file = new File(fileName);
        Assert.isTrue(file.exists());

        if (fileName.endsWith(".pdf")) {
            setContentType(CONTENT_TYPE_PDF);
        } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            setContentType(CONTENT_TYPE_WORD);
        }

        // IE workaround: write into byte array first.
        ByteArrayOutputStream baos = createTemporaryOutputStream();
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            StreamUtil.INSTANCE.transfer(is, baos);
            writeToResponse(response, baos);
        } catch (IOException e) {
            logger.error(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

}
